<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <img src="../../public/robot-icon.svg" alt="AI应用中心 Logo" class="logo" /> <!-- 您的 Logo -->
        <h2>AI应用中心</h2>
      </div>

      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="验证码登录" name="code">
          <div class="tab-content-wrapper">
            <div class="code-login-form form-container">
              <p class="login-tip">支持手机号 / 微信 / QQ邮箱 登录</p>
              
              <!-- 手机号/邮箱 输入及验证码 -->
              <el-form @submit.prevent="handleLogin('code')" label-position="top">
                <el-form-item label="">
                  <el-input v-model="account" placeholder="请输入手机号/邮箱">
                    <template #prefix>
                      <el-icon class="el-input__icon"><User /></el-icon> <!-- 图标 -->
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item label="">
                  <div class="verification-code-input">
                    <el-input v-model="verificationCode" placeholder="请输入验证码">
                      <template #prefix>
                        <el-icon class="el-input__icon"><Key /></el-icon> <!-- 图标 -->
                      </template>
                    </el-input>
                    <el-button :disabled="isSendingCode || !account" @click="sendCode">{{ codeButtonText }}</el-button>
                  </div>
                </el-form-item>

                <div class="agreement-notice">
                    注册登录即代表已阅读并同意我们的用户协议与隐私政策，未注册
                    的手机号/邮箱将在登录时自动注册
                    <!-- 实际应用中这里应该包含用户协议和隐私政策链接 -->
                </div>

                <el-form-item>
                  <el-button type="primary" native-type="submit" class="login-button" :disabled="!account || !verificationCode">登录</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <!-- 微信扫码登录 -->
            <el-divider direction="vertical" class="vertical-divider"></el-divider>

            <div class="qrcode-container">
              <div class="qrcode-wrapper">
                <vue-qrcode v-if="wxUrl && !isWaitingLogin" :value="wxUrl" :options="{ width: 150 }"></vue-qrcode>
                <div v-if="isWaitingLogin" class="qrcode-waiting">
                  <el-icon class="waiting-icon"><Loading /></el-icon>
                  <p>等待用户授权登录...</p>
                </div>
              </div>
              <div class="qrcode-tip-wrapper">
                <p class="qrcode-tip">{{ isWaitingLogin ? '等待授权中...' : '请使用微信扫码登录' }}</p>
                <el-icon v-if="!isWaitingLogin" class="refresh-icon" @click="refreshQrCode"><Refresh /></el-icon>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="密码登录" name="password">
          <div class="tab-content form-container">
            <el-form @submit.prevent="handleLogin('password')" label-position="top">
              <el-form-item label="">
                <el-input v-model="username" placeholder="请输入用户名/手机号">
                  <template #prefix>
                    <el-icon class="el-input__icon"><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input type="password" v-model="password" placeholder="请输入密码" show-password>
                  <template #prefix>
                    <el-icon class="el-input__icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 验证码图片及输入框 -->
              <el-form-item label="">
                <div class="captcha-input-wrapper">
                  <el-input v-model="captchaInput" placeholder="请输入验证码">
                    <template #prefix>
                      <el-icon class="el-input__icon"><Key /></el-icon>
                    </template>
                  </el-input>
                  <img :src="verifyCode" @click="fetchCaptcha" alt="" class="captcha-image" />
                </div>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" native-type="submit" class="login-button" :disabled="!username || !password">登录</el-button>
              </el-form-item>
            </el-form>
            <!-- 可以添加忘记密码等链接 -->
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="oauth-login">
        <!-- 其他可能的第三方登录按钮 -->
         <!-- 移除了 GitHub 登录按钮 -->
      </div>

    </el-card>
  </div>
</template>

<script setup>
import {ref, watch, onUnmounted, onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { login } from '../state/auth';
import { setUserData } from '../state/user';
import { ElMessage } from 'element-plus';
import { User, Key, Lock, HomeFilled, Refresh, Loading } from '@element-plus/icons-vue';
import {captchaAPI, emailCodeAPI} from "../api/code/code.js";
import {getWxCodeAPI, loginEmailAPI, loginPhoneAPI} from "../api/login/login.js";
import {connectionSendWxTicketUrl, initConnection} from "../ws/websocket.js";

const router = useRouter();
const activeTab = ref('code'); // 默认激活验证码登录 Tab
const wxUrl = ref(''); // 微信登录 URL


// 验证码登录
const account = ref(''); // 手机号或邮箱
const verificationCode = ref(''); // 短信验证码
const isSendingCode = ref(false);
const codeButtonText = ref('发送验证码');
let codeTimer = null;

// 账户密码登录
const username = ref('');
const password = ref('');
const captchaInput = ref(''); // 用户输入的验证码(图片)
const verifyCode = ref(''); // 验证码图片URL
const verifyCodeKey = ref(''); // 验证码 key
const code = ref(''); // 验证码图片验证码

const userAccountFirst = ref(''); // 用户账号
const userPasswordFirst = ref(''); // 用户密码

const isWaitingLogin = ref(false); // 是否正在等待微信登录授权

const sendCode = async () => {
  if (!account.value) {
    ElMessage.warning('请输入手机号或邮箱！');
    return;
  }
  if (!isRightPhoneOrEmail(account.value)){
    ElMessage.warning('请输入正确的手机号或邮箱！');
    return;
  }
  let isSendSuccess = false;
  //判断到底是发送邮箱还是手机号
  if (isPhoneRight(account.value)){
    isSendSuccess = true;
  }else if (isEmailRight(account.value)){
    const res = await emailCodeAPI(account.value);
    if (res.code === 200) {
      isSendSuccess = true;
    }
  }
  if (isSendSuccess){
    // 实际应用中这里需要调用后端接口发送验证码
    ElMessage.success(`验证码已发送到 ${account.value}`);
    isSendingCode.value = true;
    let seconds = 60;
    codeButtonText.value = `重新发送 (${seconds}s)`;
    codeTimer = setInterval(() => {
      seconds--;
      if (seconds > 0) {
        codeButtonText.value = `重新发送 (${seconds}s)`;
      } else {
        isSendingCode.value = false;
        codeButtonText.value = '发送验证码';
        clearInterval(codeTimer);
        codeTimer = null; // 清除定时器引用
      }
    }, 1000);
  }
};



// 获取验证码图片
const fetchCaptcha = async () => {
  const res = await captchaAPI();
  if (res.code === 200) {
    verifyCode.value = res.data?.verifyCode;
    verifyCodeKey.value = res.data?.verifyCodeKey;
    code.value = res.data?.code;
  }
  console.log('res', res);
};

// 监听 activeTab 变化，如果是密码登录，则获取验证码
watch(activeTab, (newValue) => {
  if (newValue === 'password') {
    fetchCaptcha();
  }
});

// 在组件 mounted 时检查是否是密码登录，如果是，则获取验证码 (以防直接进入密码登录页面)
// Element Plus 的 ElTabs 会在 mounted 后才触发 activeTab 的 watch，所以这里也需要检查一下
// 或者更可靠的做法是在合适的生命周期钩子中调用 fetchCaptcha

// 第三方登录 (目前不包含 GitHub 和微信)
const handleOAuthLogin = (provider) => {
   console.log(`Attempting OAuth login with ${provider}, not implemented.`);
   ElMessage.info(`暂不支持通过 ${provider} 登录。`);
};

const handleLogin = async (type) => {
  // 实际应用中，这里根据不同的 type 调用不同的后端登录接口
  console.log(`Attempting ${type} login`);
  let loginSuccess = false;
  if (type === 'code') {
    if (!account.value || !verificationCode.value) {
      ElMessage.warning('请输入手机号/邮箱和验证码！');
      return;
    }
    // 实际应用中调用手机号/邮箱验证码登录接口进行验证
    // 校验手机号/邮箱验证码是否正确，如果正确，则登录成功并设置用户信息
    if (!isRightPhoneOrEmail(account.value)){
      ElMessage.warning('请输入手机号/邮箱');
      return;
    }
    //是否为邮箱登录
    if (isEmailRight(account.value)){
      const data = {
        "email" : account.value,
        "code" : verificationCode.value
      }
      const res = await loginEmailAPI(data);
      if (res.code === 202){//登录成功状态码
        console.log('202进入登录成功流程');
        if (res.data.isFirstLogin){//说明第一次登录认证，需要注册
          console.log('第一次登录，需要注册');
          userAccountFirst.value = res.data?.userAccount;
          //跳转到注册页面
          router.push({ name: 'FirstLoginSetup', params: { userAccount: userAccountFirst.value } }); // 跳转到首次登录设置页面
        }else {
          ElMessage.success('登录成功！');
          login();
          const redirectPath = router.currentRoute.value.query.redirect || '/home';
          router.push(redirectPath);
        }
      }
    }else if (isPhoneRight(account.value)){
      const data = {
        "phone" : account.value,
        "code" : verificationCode.value
      }
      const res = await loginPhoneAPI(data);
      if (res.code === 202){
        console.log('202进入登录成功流程');
        if (res.data.isFirstLogin){//说明第一次登录认证，需要注册
          console.log('第一次登录，需要注册');
          userAccountFirst.value = res.data?.userAccount;
          //跳转到注册页面
          router.push({ name: 'FirstLoginSetup', params: { userAccount: userAccountFirst.value } }); // 跳转到首次登录设置页面
        }else {
          login();
          ElMessage.success('登录成功！');
          const redirectPath = router.currentRoute.value.query.redirect || '/home';
          router.push(redirectPath);
        }
      }
    }else {
      ElMessage.warning('请输入手机号/邮箱');
      return;
    }
  } else if (type === 'password') {
    if (!username.value || !password.value || !captchaInput.value) { // 增加验证码校验
      ElMessage.warning('请输入用户名、密码和验证码！');
      return;
    }
    // 实际应用中调用账户密码登录接口，并包含验证码进行验证
    if ((username.value === 'test' && password.value === '123456' && captchaInput.value === 'mockcode') || (username.value === 'admin' && password.value === 'admin' && captchaInput.value === 'mockcode')) { // 模拟验证码校验
      login();
      setUserData({
        username: username.value,
        preferences: '喜欢编程、阅读',
        status: 'single',
        tokens: 500
      });
      ElMessage.success('登录成功！');
      const redirectPath = router.currentRoute.value.query.redirect || '/';
      router.push(redirectPath);
    } else {
      ElMessage.error('用户名或密码错误！');
    }
  }
};

// 清理定时器
onUnmounted(() => {
  if (codeTimer) {
    clearInterval(codeTimer);
  }
});


onMounted(async ()=>{
  initConnection();//建立websocket连接
})

// 监听微信二维码返回事件
window.addEventListener('wx-ticket',function (event){
  console.log('监听微信二维码返回事件Login',event)
  //获取到ticketUrl
  wxUrl.value = event.detail.data.loginUrl;
});


// 监听微信二维码扫码等待登录授权事件
window.addEventListener('wx-login-waiting',function (event){
  isWaitingLogin.value = true;
  console.log('openId对应的uuid值',event.detail.data.uuid)
  localStorage.setItem('ai_love_uuid',event.detail.data.uuid);
});


// 监听微信扫码登录成功
window.addEventListener('wx-login-success',function (event){
  localStorage.setItem('accessToken',event.detail.data.accessToken);
  localStorage.setItem('uuid',event.detail.data.uuid);
  login(); // 模拟登录状态
  ElMessage.success('登录成功！');
  router.push('/home');
});

// 监听登录授权成功，进入email认证
window.addEventListener('wx-login-success-email',function (event){
  ElMessage.info('需要进行邮箱认证');
  router.push('/email-auth');
});



const isPhoneRight = (value) => {
  if (value == null || value.trim() === ''){
    return false;
  }
  //验证手机号是否正确
  if (/^[1][3,4,5,7,8][0-9]{9}$/.test(value)){
    return true;
  }
  return false;
}

const isEmailRight = (value) => {
  if (value == null || value.trim() === ''){
    return false;
  }
  //验证qq邮箱是否正确
  if (/^[a-zA-Z0-9_-]+@qq\.com$/.test(value)){
    return true;
  }
  return false;
}


// 校验手机号/邮箱是否正确
const isRightPhoneOrEmail = (value) => {
  if (value == null || value.trim() === ''){
    return false;
  }
  return isPhoneRight(value) || isEmailRight(value);
}
//校验验证码是否正确
const isRightCaptcha = () => {
  if (code.value === captchaInput.value){
    return true;
  }
  return false;
}

// 刷新二维码
const refreshQrCode = async () => {
  if (isWaitingLogin.value) {
    ElMessage.warning('等待授权中，请稍后再试');
    return;
  }
  try {
    await connectionSendWxTicketUrl();
    ElMessage.success('二维码已刷新');
  } catch (error) {
    ElMessage.error('刷新失败，请重试');
  }
};

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #1a1a2e; /* 深色背景 */
  padding: 20px;
}

.login-card {
  width: 800px; /* 调整宽度以容纳两侧内容 */
  max-width: 95%; /* 移动端最大宽度 */
  padding: 40px; /* 增加内边距 */
  border-radius: 12px; /* 圆角 */
  background-color: #2a2a40; /* 深色卡片背景 */
  color: #ffffff; /* 文本颜色 */
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6); /* 阴影 */
  border: 1px solid #404060; /* 边框 */
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: column; /* 内部元素垂直排列 */
  align-items: center; /* 居中 */
}

.login-header {
    margin-bottom: 30px;
    text-align: center; /* 居中文本 */
    display: flex;
    align-items: center;
    justify-content: center;
}

.login-header img {
    height: 50px; /* 调整 Logo 大小 */
    margin-right: 10px; /* 调整 Logo 右侧间距 */
}

.login-header h2 {
    color: #66b1ff; /* 标题颜色 */
    font-size: 1.8em; /* 标题字号 */
    text-shadow: 0 0 8px #66b1ff; /* 标题阴影 */
}

.login-tabs {
    width: 100%; /* Tab 宽度占满 */
}

.login-tabs :deep(.el-tabs__item) {
    color: #b3b3b3; /* Tab 标题颜色 */
    font-size: 1.1em;
}

.login-tabs :deep(.el-tabs__item.is-active) {
    color: #66b1ff; /* 选中 Tab 标题颜色 */
    font-weight: bold;
}

.login-tabs :deep(.el-tabs__active-bar) {
    background-color: #66b1ff; /* 选中 Tab 下划线颜色 */
}

.login-tabs :deep(.el-tabs__nav-wrap::after) {
    background-color: #404060; /* Tab 下方的细线颜色 */
}

.tab-content-wrapper {
    display: flex; /* 使用 Flexbox 布局 */
    justify-content: center; /* 内容居中 */
    gap: 40px; /* 表单和二维码之间的间距 */
    padding: 20px 0;
    flex-wrap: wrap; /* 允许换行 */
}

.form-container {
    width: 350px; /* 固定表单容器宽度 */
    max-width: 100%; /* 确保不超过父容器 */
}

.tab-content {
    padding: 20px 0;
}

.login-tip {
    text-align: center;
    color: #b3b3b3; /* 提示文本颜色 */
    font-size: 0.9em;
    margin-bottom: 20px;
}

.el-form-item__label {
    color: #b3b3b3 !important; /* 调整 label 颜色 */
    font-size: 1em !important;
    margin-bottom: 5px !important;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-input__inner {
    background-color: #3a3a50 !important; /* 输入框背景色 */
    border-color: #404060 !important; /* 输入框边框颜色 */
    color: #ffffff !important; /* 输入框文本颜色 */
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.3) !important; /* 添加内阴影 */
    border-radius: 4px; /* 调整圆角 */
}

.el-input__inner::placeholder {
    color: #b3b3b3;
}

.verification-code-input {
    display: flex;
    gap: 10px;
    align-items: center;
}

.verification-code-input .el-input {
    flex: 1;
}

.agreement-notice {
    color: #b3b3b3; /* 调整文本颜色 */
    font-size: 0.8em;
    margin-top: -10px; /* 调整与上方表单的间距 */
    margin-bottom: 20px;
    text-align: center;
}

.el-button.login-button {
    width: 100%;
    margin-top: 10px;
    font-size: 1.1em;
    padding: 12px 20px;
    border-radius: 4px; /* 调整按钮圆角 */
}

.vertical-divider {
    height: 200px; /* 调整分割线高度 */
}

.oauth-login {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
}

/* 第三方登录按钮样式 */
.oauth-login .el-button {
    font-size: 1em;
    color: #b3b3b3; /* 调整链接颜色 */
}

.oauth-login .el-button:hover {
    color: #ffffff; /* Hover 颜色 */
}

/* 调整 Element Plus 图标颜色 */
.el-input__prefix-inner {
    color: #b3b3b3; /* 图标颜色 */
}

.captcha-input-wrapper {
  display: flex;
  align-items: center;
  gap: 10px; /* Space between input and image */
}

.captcha-input-wrapper .el-input {
  flex: 1; /* Allow input to take available space */
}

.captcha-image {
  width: 100px; /* Adjust as needed */
  height: 40px; /* Adjust as needed */
  cursor: pointer;
  border: 1px solid #404060; /* Match input border style */
  border-radius: 4px; /* Match input border radius */
  object-fit: cover; /* Ensure image covers the area without distortion */
}

.qrcode-container {
  padding-left: 0; /* 移除左侧间距 */
  border-left: none; /* 移除左侧边框 */
  display: flex;
  align-items: center;
  flex-direction: column; /* 垂直排列 */
}

.qrcode-tip-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
  justify-content: center;
}

.qrcode-tip {
  font-size: 0.8em;
}

.refresh-icon {
  cursor: pointer;
  font-size: 18px;
  color: #b3b3b3;
  transition: all 0.3s ease;
}

.refresh-icon:hover {
  color: #66b1ff;
  transform: rotate(180deg);
}

.qrcode-wrapper {
  position: relative;
  width: 150px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qrcode-waiting {
  width: 150px;
  height: 150px;
  background-color: rgba(42, 42, 64, 0.9);
  border: 1px solid #404060;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.waiting-icon {
  font-size: 32px;
  color: #66b1ff;
  animation: rotate 1s linear infinite;
}

.qrcode-waiting p {
  color: #66b1ff;
  font-size: 14px;
  margin: 0;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .login-card {
    width: 98%; /* 移动端调整宽度 */
    padding: 30px 20px; /* 移动端调整内边距 */
  }

  .login-header {
      margin-bottom: 20px;
  }

  .login-header img {
      height: 40px; /* 移动端调整 Logo 大小 */
  }

  .login-header h2 {
      font-size: 1.6em; /* 移动端调整标题字号 */
  }

  .login-tabs :deep(.el-tabs__item) {
      font-size: 1em;
  }

  .tab-content-wrapper {
      flex-direction: column; /* 移动端垂直堆叠 */
      gap: 20px; /* 调整间距 */
      padding: 15px 0;
  }

  .form-container {
      width: 100%; /* 移动端宽度占满 */
  }

    .tab-content {
        padding: 15px 0;
    }

    .login-tip {
        font-size: 0.8em;
        margin-bottom: 15px;
    }

    .el-form-item {
        margin-bottom: 15px;
    }

    .agreement-notice {
        font-size: 0.7em;
        margin-bottom: 15px;
    }

    .el-button.login-button {
        font-size: 1em;
        padding: 10px 15px;
    }

    .vertical-divider {
        display: none; /* 移动端隐藏垂直分割线 */
    }

    .qrcode-container {
        padding-left: 0; /* 移除左侧间距 */
        border-left: none; /* 移除左侧边框 */
        padding-top: 20px; /* 顶部间距 */
        border-top: 1px solid #404060; /* 添加顶部边框 */
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-direction: column; /* 垂直排列 */
    }

    .qrcode-tip {
        font-size: 0.8em;
        margin-top: 10px;
    }

    .oauth-login {
        flex-direction: column; /* 移动端垂直排列 */
        gap: 10px;
        margin-top: 15px;
    }

    .oauth-login .el-button {
        font-size: 0.9em;
    }
}
</style> 